import fs from 'fs';
import path from 'path';
import os from 'os'

export const getFileTypeName = (fileName: string) => {
  const match = fileName.match(/\.(\w+)$/);
  return match ? match[1] : "unknow";
};

export const getNameByLink = (link: string) => {
  const arr = link.split("/");
  const name = arr[arr.length - 1] || "";
  return decodeURIComponent(name);
};

// 得到图片的base64
export const fileImgToBase64Url = async (file: File) => {
  return new Promise((res) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      const base64Value = e.target.result;
      // target.result 该属性表示目标对象的DataURL
      res(base64Value);
    };
    reader.readAsDataURL(file);
  });
};

export const bufferToBase64Url = (data: string, type: string) => {
  const buffer = new Buffer(data, 'binary');
  return `data:image/${type};base64,` + buffer.toString('base64');
}

const getFilePath = () => {
  return path.resolve(os.homedir(), 'Download/', `${new Date().getTime()}-screent-shot.png`)
}

export const fileReaderAsBuffer = async (file: File) => {
  const filePath = getFilePath();
  return new Promise((res) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      const arrayBuffer = e.target.result as ArrayBuffer;
      const unit8Array = new Uint8Array(arrayBuffer);
      const buffer = new Buffer(arrayBuffer);
      fs.writeFileSync(filePath, buffer);
      const imageObj = {
        lastModified: file.lastModified,
        //@ts-ignore 
        lastModifiedDate: file.lastModifiedDate,
        name: file.name,
        path: filePath,
        size: file.size,
        type: file.type,
        //@ts-ignore 
        webkitRelativePath: file.webkitRelativePath,
        fileContent: unit8Array,
      };
      res(imageObj);
    };
    reader.readAsArrayBuffer(file);
  })
}

const getImageType = str => {
  const reg = /\.(png|jpg|gif|jpeg|webp)$/;
  return str.match(reg)[1];
}

export const localFileToBase64 = (url) => {
  return new Promise((resolve, reject) => {
    fs.readFile(url, 'binary', (err, data) => {
      if(err) {
        reject(err);
      } else {
        const base64Url = bufferToBase64Url(data, getImageType(url));
        resolve(base64Url);
      }
    })
  });
}

export const getFileByPath = async (filePath) => {
  const size = fs.statSync(filePath).size;
  const name = path.parse(filePath).base;
  const type = name.split('.')[1];
  const fileContent = await fs.readFileSync(filePath);
  return {
    path: filePath,
    size,
    name,
    type,
    fileContent
  }
}